const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
require('dotenv').config();

const { sequelize } = require('./config/database');
const productRoutes = require('./routes/products');
const analyticsRoutes = require('./routes/analytics');
const webhookRoutes = require('./routes/webhook');
const aiRoutes = require('./routes/ai');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(helmet());
app.use(cors());
app.use(morgan('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '../public')));

// 路由
app.use('/api/products', productRoutes);
app.use('/api/analytics', analyticsRoutes);
app.use('/api/webhook', webhookRoutes);
app.use('/api/ai', aiRoutes);

// 首页路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../views/index.html'));
});

// 数据库连接测试
async function initializeDatabase() {
    try {
        await sequelize.authenticate();
        console.log('数据库连接成功');
        
        // 同步模型
        await sequelize.sync({ alter: true });
        console.log('数据库模型同步完成');
    } catch (error) {
        console.error('数据库连接失败:', error);
    }
}

// 启动服务器
app.listen(PORT, async () => {
    console.log(`AIWOO服务器运行在端口 ${PORT}`);
    await initializeDatabase();
});

module.exports = app;
